#include <xp/bas/string.h>
#include <xp/bas/stdio.h>
#include <xp/bas/locale.h>

#ifdef linux
#define _GNU_SOURCE
#endif

#ifndef _WIN32
#include <fnmatch.h>
#endif

#ifndef FNM_IGNORECASE
#define FNM_IGNORECASE FNM_CASEFOLD
#endif

#ifndef _WIN32
xp_bool_t aa_fnmatch (const char* s, const char* p, int flags)
{
	return fnmatch (p, s, flags) == 0;
}
#endif

int xp_main (int argc, xp_char_t* argv[])
{
	const xp_char_t* data[] = 
	{
		XP_TEXT(""),
		XP_TEXT("/"),
		XP_TEXT("."),
		XP_TEXT(".."),
		XP_TEXT("/../."),
		XP_TEXT("/././.."),
		XP_TEXT(".hidden"),
		XP_TEXT("/bin/ls"),
		XP_TEXT("/bin/ls/."),
		XP_TEXT("/bin/awk"),
		XP_TEXT("/.profile"),
		XP_TEXT("/etc/passwd"),
		XP_TEXT("/usr/local/bin/ls"),
		XP_TEXT("/usr/local/.profile/bacon"),
		XP_TEXT("/usr/local/.profile/.bacon"),
		XP_NULL
	};
	const xp_char_t** p = data;

	xp_setlocale ();

	if (argc != 2) {
		xp_fprintf (xp_stderr, XP_TEXT("usage: %s pattern\n"), argv[0]);
		return -1;
	}
	
	while (*p != XP_NULL) {
		xp_mchar_t buf[10000], buf2[10000];

		xp_printf (XP_TEXT("xp_strfnmat (%s, %s, 0) ==> %d\n"),
			*p, argv[1], xp_strfnmat (*p, argv[1], 0));

		xp_printf (XP_TEXT("xp_strfnmat (%s, %s, %d) ==> %d\n"),
			*p, argv[1], XP_STRFNMAT_PERIOD,
			xp_strfnmat (*p, argv[1], XP_STRFNMAT_PERIOD));

		xp_printf (XP_TEXT("xp_strfnmat (%s, %s, %d) ==> %d\n"),
			*p, argv[1], XP_STRFNMAT_PATHNAME,
			xp_strfnmat (*p, argv[1], XP_STRFNMAT_PATHNAME));

		xp_printf (XP_TEXT("xp_strfnmat (%s, %s, %d) ==> %d\n"),
			*p, argv[1], XP_STRFNMAT_PATHNAME | XP_STRFNMAT_CASEFOLD,
			xp_strfnmat (*p, argv[1], XP_STRFNMAT_PATHNAME | XP_STRFNMAT_CASEFOLD));

		xp_printf (XP_TEXT("xp_strfnmat (%s, %s, %d) ==> %d\n"),
			*p, argv[1], XP_STRFNMAT_PERIOD | XP_STRFNMAT_PATHNAME,
			xp_strfnmat (*p, argv[1], XP_STRFNMAT_PERIOD | XP_STRFNMAT_PATHNAME));
		xp_printf (XP_TEXT("xp_strfnmat (%s, %s, %d) ==> %d\n"),
			*p, argv[1], XP_STRFNMAT_PERIOD | XP_STRFNMAT_PATHNAME | XP_STRFNMAT_CASEFOLD,
			xp_strfnmat (*p, argv[1], XP_STRFNMAT_PERIOD | XP_STRFNMAT_PATHNAME | XP_STRFNMAT_CASEFOLD));

		xp_wcstomcs (*p, buf, xp_sizeof(buf));
		xp_wcstomcs (argv[1], buf2, xp_sizeof(buf2));

#ifndef _WIN32
		printf ("aa_fnmatch (%s, %s, 0) ==> %d\n",
			buf, buf2, aa_fnmatch (buf, buf2, 0));

		printf ("aa_fnmatch (%s, %s, %d) ==> %d\n",
			buf, buf2, FNM_PERIOD,
			aa_fnmatch (buf, buf2, FNM_PERIOD));

		printf ("aa_fnmatch (%s, %s, %d) ==> %d\n",
			buf, buf2, FNM_PATHNAME,
			aa_fnmatch (buf, buf2, FNM_PATHNAME));

		printf ("aa_fnmatch (%s, %s, %d) ==> %d\n",
			buf, buf2, FNM_PERIOD | FNM_PATHNAME,
			aa_fnmatch (buf, buf2, FNM_PERIOD | FNM_PATHNAME));

		printf ("aa_fnmatch (%s, %s, %d) ==> %d\n",
			buf, buf2, FNM_PERIOD | FNM_PATHNAME | FNM_IGNORECASE,
			aa_fnmatch (buf, buf2, FNM_PERIOD | FNM_PATHNAME | FNM_IGNORECASE));
#endif

		xp_printf (XP_TEXT("-----------------------\n"));
		p++;
	}

	return 0;
}
